layui.define(['layer', 'table'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;

    var treetable = {
		params:{},
        // 渲染树形表格
        render: function (param) {
			this.params = param
            // 检查参数
            if (!treetable.checkParam(param)) {
                return;
            }
            // 获取数据
            if (param.data) {
                treetable.init(param, param.data);
            } else {
                /*$.getJSON(param.url, param.where, function (res) {
                    treetable.init(param, res.data);
                });*/
				var method = "GET"
				if (typeof param.method != "undefined"){
					method = param.method
				}
				$.ajax({
					type: method,
					url: param.url,
					data: param.where,
					dataType: "json",
					success: function(res){
						treetable.init(param, res.data);
					}
				});
				
            }
        },
        // 渲染表格
        init: function (param, datas) {
            var mData = [];
            var doneCallback = param.done;
            var data = datas.data
			var menu_ids = datas.menu_ids
			
			if(data){
				var tNodes = data;
				// 补上id和pid字段
				for (var i = 0; i < tNodes.length; i++) {
					var tt = tNodes[i];
					if (!tt.id) {
						if (!param.treeIdName) {
							layer.msg('参数treeIdName不能为空', {icon: 5});
							return;
						}
						tt.id = tt[param.treeIdName];
					}
					if (!tt.pid) {
						if (!param.treePidName) {
							layer.msg('参数treePidName不能为空', {icon: 5});
							return;
						}
						tt.pid = tt[param.treePidName];
					}
				}
			

				// 对数据进行排序
				var sort = function (s_pid, data) {
					for (var i = 0; i < data.length; i++) {
						if (data[i].pid == s_pid) {
							var len = mData.length;
							if (len > 0 && mData[len - 1].id == s_pid) {
								mData[len - 1].isParent = true;
							}
							mData.push(data[i]);
							sort(data[i].id, data);
						}
					}
				};
				sort(param.treeSpid, tNodes);
			}
            // 重写参数
			
            param.url = undefined;
            param.data = mData;
            param.page = {
                count: param.data.length,
                limit: param.data.length
            };
            param.cols[0][param.treeColIndex].templet = function (d) {
				
                var mId = d.id;
                var mPid = d.pid;
                var isDir = d.isParent;
                var emptyNum = treetable.getEmptyNum(mPid, mData);
                var iconHtml = '';
                for (var i = 0; i < emptyNum; i++) {
                    iconHtml += '<span class="treeTable-empty"></span>';
                }
                if (isDir) {
                    iconHtml += '<i class="layui-icon layui-icon-triangle-d"></i> <i class="layui-icon layui-icon-layer"></i>';
                } else {
                    iconHtml += '<i class="layui-icon layui-icon-file"></i>';
                }
                iconHtml += '&nbsp;&nbsp;';
                var ttype = isDir ? 'dir' : 'file';
                var vg = '<span class="treeTable-icon open" lay-tid="' + mId + '" lay-tpid="' + mPid + '" lay-ttype="' + ttype + '">';
                
				var checkboxHtml = ""
				if (typeof param.checkboxHtml != "undefined" && param.checkboxHtml == true){
					//节点是否选中
					var isChecked = ""
					if (menu_ids){
						if ($.inArray(mId, menu_ids) > -1){
							isChecked = "checked"
						}
					}
					checkboxHtml = '<input type="checkbox" lay-filter="lay-filter" '+isChecked+' class="checkbox-menu checkbox_id_'+mId+' checkbox_pid_'+mPid+'" data-pid="'+mPid+'" name="checkmenu[]" lay-skin="primary" title="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+d[param.cols[0][param.treeColIndex].field]+'" value="'+mId+'" >'
				}else{
					checkboxHtml = d[param.cols[0][param.treeColIndex].field];
				}
				return vg + iconHtml + checkboxHtml  + '</span>'
            };

            param.done = function (res, curr, count) {
                $(param.elem).next().addClass('treeTable');
                $('.treeTable .layui-table-page').css('display', 'none');
                $(param.elem).next().attr('treeLinkage', param.treeLinkage);
                // 绑定事件换成对body绑定
                /*$('.treeTable .treeTable-icon').click(function () {
                    treetable.toggleRows($(this), param.treeLinkage);
                });*/
                if (param.treeDefaultClose) {
                    treetable.foldAll(param.elem);
                }
                if (doneCallback) {
                    doneCallback(res, curr, count);
                }
            };

            // 渲染表格
            table.render(param);
        },
        // 计算缩进的数量
        getEmptyNum: function (pid, data) {
            var num = 0;
            if (!pid) {
                return num;
            }
            var tPid;
            for (var i = 0; i < data.length; i++) {
                if (pid == data[i].id) {
                    num += 1;
                    tPid = data[i].pid;
                    break;
                }
            }
            return num + treetable.getEmptyNum(tPid, data);
        },
        // 展开/折叠行
        toggleRows: function ($dom, linkage) {
            var type = $dom.attr('lay-ttype');
            if ('file' == type) {
                return;
            }
            var mId = $dom.attr('lay-tid');
            var isOpen = $dom.hasClass('open');
            if (isOpen) {
                $dom.removeClass('open');
            } else {
                $dom.addClass('open');
            }
            $dom.closest('tbody').find('tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var pid = $ti.attr('lay-tpid');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if (mId == pid) {
                    if (isOpen) {
                        $(this).hide();
                        if ('dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    } else {
                        $(this).show();
                        if (linkage && 'dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    }
                }
            });
        },
        // 检查参数
        checkParam: function (param) {
            if (!param.treeSpid && param.treeSpid != 0) {
                layer.msg('参数treeSpid不能为空', {icon: 5});
                return false;
            }

            if (!param.treeColIndex && param.treeColIndex != 0) {
                layer.msg('参数treeColIndex不能为空', {icon: 5});
                return false;
            }
            return true;
        },
        // 展开所有
        expandAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && !tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        // 折叠所有
        foldAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        // 重新加载
        reload: function (params) {
			delete params.data
			this.render(params)
        },
		// 权限节点 checkbox,上下级联动
        checkboxToggleRows: function ($dom) {
            var this_id = $dom.parent().find(".checkbox-menu").val();
			var this_pid = $dom.parent().find(".checkbox-menu").attr("data-pid");
			var this_action = $dom.attr("action");
			//console.log(this_id+'----- pid:'+this_pid+"----action:"+this_action);
			//初始化标记
			$('.treeTable .layui-form-checkbox').attr("action","");
			if($dom.parent().find(".checkbox-menu").is(':checked')){
				//复选框被选中
				
				//父节点未选中时 
				if($(document).find(".checkbox_id_"+this_pid).is(':checked') == false){
					//操作: 选中父节点
					var $pdom = $(document).find(".checkbox_id_"+this_pid).parent().find(".layui-form-checkbox")
					//标记
					$pdom.attr("action","parent_click")
					$pdom.click(); //jq 触发点击事件
					
				}
				//父节点递归时不操作子节点
				if (this_action =="parent_click") return false;
				
				//子节点操作
				var $cdom = $(document).find(".checkbox_pid_"+this_id)
				if ($cdom.length >0){
					$cdom.each(function(i,val) {
						//未选中
						if($(val).is(':checked') == false){
							//操作 子节点选中
							//标记
							$(val).parent().find(".layui-form-checkbox").attr("action","child_click")
							$(val).parent().find(".layui-form-checkbox").click();//jq 触发点击事件
						}
					});
				}
				
			}else{
				
				//执行操作 遍历子节点取消选中
				//子节点操作
				//table.reload('role-menu-table')
				var $cdom = $(document).find(".checkbox_pid_"+this_id)
				if ($cdom.length >0){
					$cdom.each(function(i,val) {
						//未选中
						if($(val).is(':checked') == true){
							//操作 子节点选中
							$(val).parent().find(".layui-form-checkbox").click();
						}
					});
				}
			} 
        },
    };

    layui.link(layui.cache.base + 'treetable-lay/treetable.css');

    // 给图标列绑定事件
    $('body').on('click', '.treeTable .treeTable-icon', function () {
        var treeLinkage = $(this).parents('.treeTable').attr('treeLinkage');
        if ('true' == treeLinkage) {
            treetable.toggleRows($(this), true);
        } else {
            treetable.toggleRows($(this), false);
        }
    });
	
	// 给复选框列绑定事件
    $('body').on('click', '.treeTable .layui-form-checkbox',{name:""}, function (e,v) {
		e.stopPropagation();    //  阻止事件冒泡
		
		//上下级 联动
		treetable.checkboxToggleRows($(this));
	
    });

    exports('treetable', treetable);
});
